﻿using System;
using System.Collections.Generic;
using System.IO;
using Nutilities.Net;

namespace Auktionshuset
{
    public class Auction : IBinaryWriteable
    {
        public int Id { get; set; }

        public string Title { get; set; }
        public string Description { get; set; }
        public string Owner { get; set; }

        public byte[] ImageBytes { get; set; }

        public decimal CurrentBid { get; set; }
        public decimal NextBid { get; set; }

        public DateTime Starts { get; set; }
        public DateTime Ends { get; set; }

        public bool Active { get; set; }

        public User HighestBidder { get; set; }

        public string StatusMessage { get; set; }

        public static Auction ReadFrom(BinaryReader reader)
        {
            return new Auction
            {
                Id = reader.ReadInt32(),

                Title = reader.ReadString(),
                Description = reader.ReadString(),
                Owner = reader.ReadString(),

                ImageBytes = reader.ReadBytes(reader.ReadInt32()),

                CurrentBid = reader.ReadDecimal(),
                NextBid = reader.ReadDecimal(),

                Starts = DateTime.FromBinary(reader.ReadInt64()),
                Ends = DateTime.FromBinary(reader.ReadInt64()),

                Active = reader.ReadBoolean(),

                HighestBidder = reader.ReadBoolean() ? User.ReadFrom(reader) : null,

                StatusMessage = reader.ReadString()
            };
        }

        public void UpdateFrom(BinaryReader reader)
        {
            // Header
            CurrentBid = reader.ReadDecimal();
            NextBid = reader.ReadDecimal();

            Active = reader.ReadBoolean();

            bool containsHighestBidder = reader.ReadBoolean();
            if (containsHighestBidder)
            {
                HighestBidder = User.ReadFrom(reader);
            }

            StatusMessage = reader.ReadString();
        }

        public void WriteTo(BinaryWriter writer)
        {
            //writer.Write(Id);

            writer.Write(Title);
            writer.Write(Description);
            //writer.Write(Owner);

            writer.Write(ImageBytes.Length);
            writer.Write(ImageBytes);

            //writer.Write(CurrentBid);
            writer.Write(NextBid);

            writer.Write(Starts.ToBinary());
            //writer.Write(Ends.ToBinary());

            //writer.Write(Active);
        }
    }
}
